import React, { createRef, PureComponent } from 'react';
import DocumentTitle from 'react-document-title';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';

import { updateOrderAddress } from '@api/home';
import request from '@service';

import { MyAddressStyle } from './style'
import { Toast } from 'antd-mobile'
import BetterScroll from 'components/betterScroll';
import { EmptyData } from '@common'


import {
  fetchAddressAction,
  updateDefaultAddress,
  selectedAddressAction
} from '@store/actionCreators'

class MyAddress extends PureComponent {
  state = {
    addressList: this.props.addressList,
    selectedKey: this.props.selectedAddresId ? this.props.selectedAddresId : '-1',
    defaultid: this.props.defaultAddress.id,
    uniacid: this.props.uniacid
  }

  adBt = createRef();


  componentDidMount() {

  }

  componentDidUpdate() {

    console.log('数据更新')

    try {
      this.adBt.current.BScroll.refresh();

    } catch (error) {

    }
  }

  render() {

    const { selectedKey, defaultid } = this.state

    const addressList = this.props.addressList

    let res = 'https://res.lexiangpingou.cn/images/826/2020/'

    return (
      <>
        <DocumentTitle title={this.props.route.title} />
        <MyAddressStyle>
          <div className="main">
            <BetterScroll style={{ height: 'calc( 100vh - 1.6rem - .32rem) ' }} ref={this.adBt}>

              {
                addressList.length > 0 &&

                addressList.map((item, key) => {
                  return (
                    <div key={key + item.tel} className="address-card flex-column">
                      <div className="top flex-row" onClick={e => { this.selectedAddress(key, item) }}>
                        <div className="left flex-column">
                          <p className="name">{item.name} <span>{item.tel}</span> </p>
                          <p className="address"> <span>{item.proc}</span> <span>{item.cityc}</span> <span>{item.countyc} </span>   </p>
                          <p className="address-detail">{item.detailed_address}</p>
                        </div>
                        <div className="right">
                          {selectedKey === item.id && <img src="https://res.lexiangpingou.cn/images/826/2020/09/fzbn8nO8WroW1yTnnz1T191772LUE2.png" alt="" />}
                        </div>
                      </div>
                      <div className="line"></div>
                      <div className="bottom flex-row">
                        <div className="set-default flex-row" onClick={e => { this.setDefaultAddres(item.id, key) }}>
                          <img src={item.id === defaultid ? res + "09/u2151MjqJj9sB7721qmU9s9s7UuJm3.png" : res + "10/pGeMlZmBiHH1ZM7dGSmi676gO1xHbz.png"} alt="" />
                          <p>设为默认地址</p>
                        </div>

                        <div className="option">
                          <button
                            className="op-bu"
                            onClick={e => { this.editAddress(item.id) }}
                          >
                            编辑
                        </button>
                          <button
                            className="op-bu"
                            style={{ marginLeft: ".4rem" }}
                            onClick={e => { this.deleteAddress(item.id, key) }}
                          >
                            删除
                      </button>

                        </div>
                      </div>
                    </div>
                  )
                })
              }

              {
                addressList.length === 0 && <EmptyData who=" 还没有地址，快去添加地址吧" />
              }
            </BetterScroll>


            <div className="add-address flex-row global-bottom-fixed" onClick={e => { this.addAddress(e) }}>
              <div className=" flex-row">
                <img src="https://res.lexiangpingou.cn/images/vip/addressbtn.png" alt="" />
                <span>添加收货地址</span>
              </div>
            </div>

          </div>
        </MyAddressStyle>
      </>
    );
  }

  editAddress(id) {
    this.props.history.push('/editaddress/' + id)
  }

  selectedAddress(key, item) {

    try {
      let entryWay = this.props.match.params.entryway
      if (entryWay === 'profile') {
        // 如果是个人中心进入不允许选择地址
        return
      } else {
        this.setState({
          selectedKey: key
        }, () => {
          // let no = window.location.hash.match(/order\/(.*)/i)[1]
          let no = JSON.parse(localStorage.getItem('UPAD_orderno'))?.value
          console.log(no)

          if (no) {
            let config = {
              deposit_orderno: no,
              province: item.proc,
              city: item.cityc,
              county: item.countyc,
              detailed_address: item.detailed_address
            }
            updateOrderAddress(config).then(res => {
              this.props.selectAddress(item)
              this.props.history.go(-1)
            })
          } else {
            this.props.history.go(-1)
          }

        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  setDefaultAddres(id) {
    //  设置默认地址

    let setdefault = {
      data: {
        action: 'morenAddress',
        uniacid: this.state.uniacid,
        id,
      }
    }

    request(setdefault).then(res => {
      if (res.status === 200) {
        this.setState({
          defaultid: id
        }, () => {
          this.props.getAddressList()
        })

      } else {
        Toast.fail('网络异常', 1)
      }
    })
  }

  addAddress(e) {
    this.props.history.push('/editaddress/add')
  }
  deleteAddress(id, key) {
    request({ data: { action: 'delAddress', id: id } }).then(res => {
      if (res.status === 200) {
        Toast.success('删除成功', 1)
        this.props.getAddressList()
        this.adBt.current.BScroll.refresh();
      } else {
        Toast.fail('删除失败', 1)
      }
    }).catch(err => console.error)

  }
}

const mapStateToProps = state => ({
  selectedAddresId: state.selectedAddress.id,
  addressList: state.addressList,
  defaultAddress: state.defaultAddress,
  uniacid: state.appConfig.uniacid
})

const mapDispatchToProps = dispatch => ({

  selectAddress(data) {
    dispatch(selectedAddressAction(data))
  },

  updateDefaultAddress(data) {
    dispatch(updateDefaultAddress(data))
  },
  getAddressList() {
    dispatch(fetchAddressAction)
  }
})

export default connect(mapStateToProps, mapDispatchToProps)(withRouter(MyAddress));